const mongoose = require("mongoose");
const fs = require("fs");
const xlsx = require("node-xlsx");
const UserQues = require("../models/UserQuesModel");
const Excel = require("../models/excelModel");
const Cities = require("../models/citiesModel");
const Areas = require("../models/areasModel");
const Streets = require("../models/streetsModel");
const Villages = require("../models/villagesModel");

exports.generateExcelDataFun = async (group) => {
  console.log("来了");
  try {
    //console.log("1");
    // const group = group;
    // console.log("2");

    let ExcelData = [
      [[], []],
      [[], []],
      [[], []],
      [[], []],
      [[], []],
      [[], []],
    ];
    let count = [0, 0, 0, 0, 0, 0];
    // console.log("3");

    let UserQuesData = [];
    if (group == "-1") {
      // console.log("4");
      UserQuesData = await UserQues.find({ state: [1, 2, 3] });
    } else {
      // console.log("5");
      UserQuesData = await UserQues.find({ group: group, state: [1, 2, 3] });
    }
    // console.log("6");

    for (let i = 0; i < UserQuesData.length; i++) {
      // console.log("问卷类型---", i, "--", UserQuesData[i].target);
      if (UserQuesData[i].target < 5) {
        ExcelData[UserQuesData[i].target].push([]);
      } else if (UserQuesData[i].target == 5 || UserQuesData[i].target == 6) {
        ExcelData[5].push([]);
      }
    }
    // console.log("7");

    // fs.unlink("./exceldata/" + group + ".xlsx", (err) => {
    //   if (err) {
    //     console.log("删除失败---", err);
    //   } else {
    //     console.log("删除成功");
    //   }
    // });
    // console.log("8");
    console.log("group---", group, "问卷长度---", UserQuesData.length);
    for (let i = 0; i < UserQuesData.length; i++) {
      // console.log(i);
      let num;
      if (UserQuesData[i].target < 5) {
        num = UserQuesData[i].target;
      } else if (UserQuesData[i].target == 5 || UserQuesData[i].target == 6) {
        num = 5;
      }
      count[num]++;
      if (count[num] == 1) {
        ExcelData[num][0].push("ID");
        ExcelData[num][0].push("state");
        ExcelData[num][1].push("问卷编号");
        ExcelData[num][1].push("状态");
      }
      ExcelData[num][count[num] + 1].push(UserQuesData[i].title);
      if (UserQuesData[i].state == 1) {
        ExcelData[num][count[num] + 1].push("待审核");
      } else if (UserQuesData[i].state == 2) {
        ExcelData[num][count[num] + 1].push("已通过");
      } else if (UserQuesData[i].state == 3) {
        ExcelData[num][count[num] + 1].push("已驳回");
      }
      for (let j = 0; j < UserQuesData[i].body.length; j++) {
        for (let k = 0; k < UserQuesData[i].body[j].contents.length; k++) {
          let t_content = UserQuesData[i].body[j].contents[k];

          if (t_content.type == 5) {
            for (let l = 0; l < t_content.title.length; l++) {
              let t_title = t_content.title[l];

              if (t_title.type == 6) {
                if (count[num] == 1 && t_title.type != -1) {
                  ExcelData[num][0].push("A1a");
                  ExcelData[num][0].push("A1b");
                  ExcelData[num][0].push("A1c");
                  ExcelData[num][0].push("A1d");
                  ExcelData[num][1].push("市");
                  ExcelData[num][1].push("县");
                  ExcelData[num][1].push("乡（镇）");
                  ExcelData[num][1].push("行政村（社区）");
                }
                let city = await Cities.findOne({
                  code: t_title.answer[0],
                });
                ExcelData[num][count[num] + 1].push(city.name);
                let country = await Areas.findOne({
                  code: t_title.answer[1],
                });
                ExcelData[num][count[num] + 1].push(country.name);
                let town = await Streets.findOne({
                  code: t_title.answer[2],
                });
                ExcelData[num][count[num] + 1].push(town.name);
                let village = "***";
                if (t_title.answer[3] != "") {
                  village = await Villages.findOne({
                    code: t_title.answer[3],
                  });
                  village = village.name;
                }
                ExcelData[num][count[num] + 1].push(village);
              } else {
                let number =
                  String.fromCharCode(j + 65) +
                  (k + 1) +
                  String.fromCharCode(l + 97);
                if (count[num] == 1 && t_title.type != -1) {
                  ExcelData[num][0].push(number);
                  ExcelData[num][1].push(t_title.title);
                }
                if (t_title.type == 1 || t_title.type == 7) {
                  if (t_title.answer == "" || !t_title.visible) {
                    ExcelData[num][count[num] + 1].push("***");
                  } else {
                    ExcelData[num][count[num] + 1].push(t_title.answer);
                  }
                } else if (t_title.type == 2) {
                  let answer = t_title.answer;
                  if (answer != -1 && t_title.visible) {
                    if (t_title.optionFlag[answer][0]) {
                      ExcelData[num][count[num] + 1].push(
                        "[" +
                          (answer + 1) +
                          "]" +
                          t_title.options[answer] +
                          "; " +
                          t_title.optionFlag[answer][1]
                      );
                    } else {
                      ExcelData[num][count[num] + 1].push(
                        "[" + (answer + 1) + "]" + t_title.options[answer]
                      );
                    }
                  } else {
                    ExcelData[num][count[num] + 1].push("***");
                  }
                } else if (t_title.type == 3) {
                  let result = "";
                  let answer = t_title.answer;
                  for (let p = 0; p < answer.length; p++) {
                    if (answer[p]) {
                      if (t_title.optionFlag[p][0]) {
                        result =
                          result +
                          "[" +
                          (p + 1) +
                          "]" +
                          t_title.options[p] +
                          "; " +
                          t_title.optionFlag[p][1];
                        ("\n");
                      } else {
                        result =
                          result +
                          "[" +
                          (p + 1) +
                          "]" +
                          t_title.options[p] +
                          "\n";
                      }
                    }
                  }
                  if (result == "" || !t_title.visible) {
                    result = "***";
                  }
                  ExcelData[num][count[num] + 1].push(result);
                }
              }
            }
          } else {
            if (count[num] == 1 && t_content.type != -1) {
              ExcelData[num][0].push(String.fromCharCode(j + 65) + (k + 1));
              ExcelData[num][1].push(t_content.title);
            }
            if (t_content.type == 1 || t_content.type == 7) {
              if (t_content.answer != "" && t_content.visible) {
                ExcelData[num][count[num] + 1].push(t_content.answer);
              } else {
                ExcelData[num][count[num] + 1].push("***");
              }
            } else if (t_content.type == 2) {
              let answer = t_content.answer;
              if (answer != -1 && t_content.visible) {
                if (t_content.optionFlag[answer][0]) {
                  ExcelData[num][count[num] + 1].push(
                    "[" +
                      (answer + 1) +
                      "]" +
                      t_content.options[answer] +
                      "; " +
                      t_content.optionFlag[answer][1]
                  );
                } else {
                  ExcelData[num][count[num] + 1].push(
                    "[" + (answer + 1) + "]" + t_content.options[answer]
                  );
                }
              } else {
                ExcelData[num][count[num] + 1].push("***");
              }
            } else if (t_content.type == 3) {
              let result = "";
              let answer = t_content.answer;
              for (let p = 0; p < answer.length; p++) {
                if (answer[p]) {
                  if (t_content.optionFlag[p][0]) {
                    result =
                      result +
                      "[" +
                      (p + 1) +
                      "]" +
                      t_content.options[p] +
                      "; " +
                      t_content.optionFlag[p][1] +
                      "\n";
                  } else {
                    result =
                      result +
                      "[" +
                      (p + 1) +
                      "]" +
                      t_content.options[p] +
                      "\n";
                  }
                }
              }
              if (result == "" || !t_content.visible) {
                result = "***";
              }
              ExcelData[num][count[num] + 1].push(result);
            }
          }
        }
      }
    }
    // console.log("9");
    const typeOptions = [
      "脱贫稳定户",
      "脱贫不稳定户",
      "突发困难严重户1",
      "突发困难严重户2",
      "边缘易致贫户",
      "其他户",
      "全部",
    ];
    // console.log("10");
    const list = [];
    for (let i = 0; i < ExcelData.length; i++) {
      if (ExcelData[i].length > 2) {
        let list_content = {
          name: typeOptions[i],
          data: ExcelData[i],
        };
        list.push(list_content);
      }
    }

    // console.log("11");
    const buffer = xlsx.build(list);
    let newdate = new Date();
    let time =
      "" +
      newdate.getFullYear() +
      "-" +
      (newdate.getMonth() + 1) +
      "-" +
      newdate.getDate() +
      "-" +
      newdate.getHours() +
      "-" +
      newdate.getMinutes();
    console.log("time---", time);
    let excelurl = "/exceldata/" + group + time + ".xlsx";
    let oldExcel = await Excel.find({ group: group });
    if (oldExcel.length != 0) {
      if (oldExcel[0].state == "success") {
        fs.unlink("." + oldExcel[0].excelurl, (err) => {
          if (err) {
            console.log("删除失败---", err);
          } else {
            console.log("删除成功");
          }
        });
      }
    }
    fs.writeFile("." + excelurl, buffer, async (error) => {
      if (error) {
        if (oldExcel.length == 0) {
          await Excel.create({
            group: group,
            state: "error",
            excelurl: error,
          });
        } else {
          await Excel.updateOne(
            { group: group },
            { state: "error", excelurl: error }
          );
        }
        console.log("生成excel失败---", group, "---", error);
      } else {
        // let ExcelUri = "http://192.168.137.1:3000" + excelurl;
        console.log("成功---地址---", excelurl);
        if (oldExcel.length == 0) {
          await Excel.create({
            group: group,
            state: "success",
            excelurl: excelurl,
          });
        } else {
          await Excel.updateOne(
            { group: group },
            { state: "success", excelurl: excelurl }
          );
        }
      }
    });
  } catch (error) {
    let oldExcel = await Excel.find({ group: group });
    if (oldExcel.length != 0) {
      if (oldExcel[0].state == "success") {
        fs.unlink("." + oldExcel[0].excelurl, (err) => {
          if (err) {
            console.log("删除失败---", err);
          } else {
            console.log("删除成功");
          }
        });
      }
    }
    if (oldExcel.length == 0) {
      await Excel.create({
        group: group,
        state: "error",
        excelurl: error,
      });
    } else {
      await Excel.updateOne(
        { group: group },
        { state: "error", excelurl: error }
      );
    }
    console.log("生成文件出错了---", error);
  }
};
